package com.happy.zebra.admin.controller;

import com.happy.zebra.admin.api.entity.PayOrder;
import com.happy.zebra.admin.mapper.PayOrderMapper;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.pay.alipay.bean.AliReturnPayBean;
import com.shycloud.mido.common.pay.alipay.bean.OrderBean;
import com.shycloud.mido.common.pay.alipay.utils.AliH5PayUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

@RestController
@AllArgsConstructor
@RequestMapping("/pay")
public class H5PayController {

    private final PayOrderMapper payOrderMapper;
    private final String callbackUrlDev = "http://0oyxpini.xiaomy.net/admin/callback";
    private final String callbackUrlProduct = "http://api.joymido.com/admin/callback";
    //1. 生成订单, 返回给前端唯一的订单号码
    //2. 调用支付宝SDK返回表单
    //3. 拉起支付宝支付
    //4. 成功进行回调
    @GetMapping("/getOrder")
    public R getOrder(BigDecimal amount){
        PayOrder payOrder = new PayOrder();
        payOrder.setAmount(amount);
        payOrderMapper.insert(payOrder);
        return new R<>(payOrder.getId());
    }

    @GetMapping("/payOrder")
    public R payOrder(String orderId, String phone){
        //根据取出订单
        PayOrder order = payOrderMapper.selectById(orderId);
        order.setPhone(phone);
        order.setStatus(1);
        payOrderMapper.updateById(order);

        OrderBean orderBean = new OrderBean();
        orderBean.setTotalAmount(order.getAmount().toString());
        orderBean.setOutTradeNo(orderId);
        orderBean.setNotifyUrl(callbackUrlDev);
        orderBean.setReturnUrl(callbackUrlDev);
        return new R<>(AliH5PayUtil.alipay(orderBean));
    }

    //支付宝成功回调
    //1. set: 实际支付金额, 手机号
    //2. 生成新的激活码
    //3. 发送激活码给用户
    @PostMapping("/callback")
    public R callback(HttpServletRequest request, AliReturnPayBean returnPay, HttpServletResponse response){
        return new R<>(returnPay);
    }
}
